package com.changgou.system.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

//ip 拦截 黑客ip
@Component//交由spring 容器
public class IpFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("IPFilter执行了");
        //获取用户请求
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostName = remoteAddress.getHostName();
        System.out.println("hostName"+hostName);
         if(blackIP(hostName)){
             //匹配黑客ip 拒绝
             ServerHttpResponse response = exchange.getResponse();
              response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return  response.setComplete();
         }

        return chain.filter(exchange);
    }

    //顺序，值越小，越先执行
    @Override
    public int getOrder() {
        return 1;
    }
//判断是否是黑客 ip
         boolean  blackIP(String hostName){
           //mysql 配置文件
             List<String> blackIpList=new ArrayList<>();
               blackIpList.add("22.22.22.22");
             for (String s : blackIpList) {
                 if(hostName.equals(s)){
                     //是黑客
                     return true;

                 }
             }
             return  false;
         }


}
